package com.xmut.xmutbackend.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmut.xmutbackend.entity.Emp;
import com.xmut.xmutbackend.entity.EmpStatistics;
import com.xmut.xmutbackend.entity.Result;
import com.xmut.xmutbackend.service.IEmpService;
import com.xmut.xmutbackend.utils.AliOSSUtils;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/emps")
public class EmpController {

    @Autowired
    private IEmpService empService;

    @Autowired
    private AliOSSUtils aliOSSUtils;


    /**
     * 分页查询员工
     */
    @GetMapping
    public Result<Map<String, Object>> page(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Byte gender,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        // 创建分页对象
        Page<Emp> pageInfo = new Page<>(page, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(name), Emp::getName, name);
        queryWrapper.eq(gender != null, Emp::getGender, gender);
        queryWrapper.ge(begin != null, Emp::getEntrydate, begin);
        queryWrapper.le(end != null, Emp::getEntrydate, end);

        // 执行分页查询
        empService.page(pageInfo, queryWrapper);

        // 封装成前端期望的数据结构
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("total", pageInfo.getTotal());      // 总记录数
        resultMap.put("rows", pageInfo.getRecords());     // 当前页数据，字段改为 rows

        return Result.success(resultMap);
    }


    @PostMapping
    public Result<Emp> add(@RequestBody Emp emp) {
        LocalDateTime now = LocalDateTime.now();
        emp.setCreateTime(now);
        emp.setUpdateTime(now);
        empService.save(emp);
        return Result.success(emp);
    }

    @PutMapping
    public Result<Emp> update(@RequestBody Emp emp) {
        if (emp.getId() == null) {
            return Result.fail("修改失败：缺少ID");
        }

        emp.setUpdateTime(LocalDateTime.now());
        boolean success = empService.updateById(emp);

        if (success) {
            return Result.success(emp);
        } else {
            return Result.fail("修改失败：数据库中不存在该ID或数据非法");
        }
    }


    @DeleteMapping("/{id}")
    public Result<String> deleteById(@PathVariable Integer id) {
        empService.removeById(id);
        return Result.success("删除成功");
    }

    @GetMapping("/{id}")
    public Result<Emp> selectById(@PathVariable Integer id) {
        Emp emp = empService.getById(id);
        return emp != null ? Result.success(emp) : Result.fail("员工不存在");
    }

    @GetMapping("/statistics")
    public Result<Object> getEmpStatistics() {
        List<Emp> empList = empService.list();  // 获取所有员工

        Map<String, Object> stats = new HashMap<>();

        // 1. 性别统计
        Map<String, Long> genderStats = empList.stream()
                .collect(Collectors.groupingBy(emp -> {
                    if (emp.getGender() == null) return "未知";
                    return emp.getGender() == 1 ? "男" : emp.getGender() == 2 ? "女" : "其他";
                }, Collectors.counting()));
        stats.put("genderStats", genderStats);

        // 2. 职位统计
        Map<String, Long> jobStats = empList.stream()
                .collect(Collectors.groupingBy(emp -> {
                    if (emp.getJob() == null) return "未知";
                    switch (emp.getJob()) {
                        case 1: return "班主任";
                        case 2: return "讲师";
                        case 3: return "学工主管";
                        case 4: return "教研主管";
                        case 5: return "咨询师";
                        default: return "其他";
                    }
                }, Collectors.counting()));
        stats.put("jobStats", jobStats);

        // 3. 部门统计
        Map<String, Long> deptStats = empList.stream()
                .collect(Collectors.groupingBy(emp -> {
                    Integer deptId = emp.getDeptId();
                    return deptId == null ? "未知部门" : "部门 " + deptId;
                }, Collectors.counting()));
        stats.put("deptStats", deptStats);

        // 4. 入职年份统计
        Map<String, Long> entryYearStats = empList.stream()
                .collect(Collectors.groupingBy(emp -> {
                    LocalDate date = emp.getEntrydate();
                    return (date == null) ? "未知" : String.valueOf(date.getYear());
                }, Collectors.counting()));
        stats.put("entryYearStats", entryYearStats);

        return Result.success(stats);
    }

    // 导出员工信息
    @GetMapping("/export")
    public void exportEmp(HttpServletResponse response) throws IOException {
        List<Emp> empList = empService.list();

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        String fileName = URLEncoder.encode("员工信息", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        try {
            EasyExcel.write(response.getOutputStream(), Emp.class)
                    .sheet("员工信息")
                    .doWrite(empList);
        } catch (Exception e) {
            e.printStackTrace();
            throw e; // 抛出去让你在控制台看到错误
        }
    }


    @PostMapping("/import")
    public Result<String> importEmp(@RequestParam("file") MultipartFile file) throws IOException {
        List<Emp> empList = EasyExcel.read(file.getInputStream())
                .head(Emp.class)
                .sheet()
                .doReadSync();

        for (Emp emp : empList) {
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
        }

        empService.saveBatch(empList);  // 批量保存
        return Result.success("导入成功，共导入" +
                " " + empList.size() + " 条数据");
    }
    //导出模板下载
    @GetMapping("/import/template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        // 1. 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("员工信息模板", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        // 2. 创建空数据模板
        List<Emp> emptyList = Collections.emptyList();

        // 3. 写入Excel
        try (OutputStream out = response.getOutputStream()) {
            EasyExcel.write(out, Emp.class)
                    .sheet("员工信息")
                    .doWrite(emptyList);
        } catch (Exception e) {
            throw new RuntimeException("模板下载失败", e);
        }
    }

    @GetMapping("/statistics/detail")
    public Result<EmpStatistics> getStatistics() {
        EmpStatistics stats = empService.getEmpStatistics();
        return Result.success(stats);
    }

}
